import { asyncRoutes, constantRoutes } from '@/router'

/**
 * 通过 meta.role 来确定当前用户是否有权限访问某个路由
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.mate && route.mate.roles) {
    return roles.some(role => route.mate.roles.includes(role))
  } else {
    return true
  }
}

/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (asyncRoutes, roles) {
  const res = []

  asyncRoutes.forEach(route => {
    const tempt = { ...route }
    if (hasPermission(roles, tempt)) {
      if (tempt.children) {
        tempt.children = filterAsyncRoutes(tempt.children, roles)
      }
      res.push(tempt)
    }
  })
  return res
}

const state = {
  routes: [], // 有权限的路由
  addRoutes: [] // 所有添加的路由？？？
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // 生成有权限的路由
  generateRoutes ({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      // 如果角色包含‘admin’，则可以拿到所有的异步路由表？
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  // namespaced表示当前模块是否使用命名空间
  // 如果使用的话，那么设置了namespaced属性的模块将和其它模块独立开来
  // 调用时得指定命名空间后才可以访问得到
  namespaced: true,
  state,
  mutations,
  actions
}
